package com.xinongbest.mall.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * @author lemonwan
 * 生成订单号工具
 */
public class OrderCodeFactory {

    /**
     * 订单类别头
     */
    private static final String ORDER_CODE = "1";

    /**
     * 随机编码
     */
    private static final int[] r = new int[]{7, 9, 6, 2, 8, 1, 3, 0, 5, 4};

    /**
     * 用户ID和随机数总长度
     */
    private static final int maxLength = 5;

    /**
     * 依据ID进行加密和随机数组成固定长度编码
     *
     * @param id
     * @return
     */
    private static String toCode(Long id) {
        String idString = id.toString();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = idString.length() - 1; i >= 0; i--) {
            stringBuilder.append(r[idString.charAt(i) - '0']);
        }
        return stringBuilder.append(getRandom(maxLength - idString.length())).toString();
    }

    /**
     * 生成固定长度随机码
     *
     * @param n
     * @return
     */
    private static long getRandom(int n) {
        long min = 0, max = 9;
        for (int i = 1; i < n; i++) {
            min *= 10;
            max *= 10;
        }
        long rangeLong = ((long) (new Random().nextDouble() * (max - min))) + min;
        return rangeLong;
    }

    /**
     * 生成时间戳
     *
     * @return
     */
    private static String getDateTime() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("HHmmss");
        return dateFormat.format(new Date());
    }

    /**
     * 生成不带类别的编码
     *
     * @param userId
     * @return
     */
    private static synchronized String getCode(Long userId) {
        userId = userId == null ? 10000 : userId;
        return getDateTime() + userId.toString();
    }

    /**
     * 生成订单编号
     *
     * @param userId
     * @return
     */
    public static String getOrderCode(Long userId) {
        return ORDER_CODE + getCode(userId);
    }

}
